package com.superpai.view.download;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

import com.superpai.R;
import com.superpai.utils.AndroidUtils;
import com.superpai.utils.BitmapUtils;
import com.superpai.utils.StringUtils;

/**
 * @author Devin.Hu
 * @date 2011-7-13
 * @version V1.0
 * @description
 */
public class AsyncImageLoader extends AsyncTask<ImageView, Void, Bitmap> {
	
	public static List<LoadImage> imageCache = new ArrayList<LoadImage>();
	private ImageView gView;

	protected Bitmap doInBackground(ImageView... views) {
		gView = views[0];
		Bitmap bitmap = null;
		String imageUrl = gView.getTag().toString();
		
		System.out.println("AsyncImageLoader imageUrl: "+ imageUrl);
		
		if (!StringUtils.isEmpty(imageUrl)) 
		{
			for (LoadImage m : imageCache) 
			{
				if (m.getUrl().equals(imageUrl)) 
				{
					SoftReference<Bitmap> softReference = m.getReference();
					if (softReference.get() != null) {
						return softReference.get();
					}
				}
			}
			checkCacheImage();
			InputStream input = doGet4stream(imageUrl);
			
			if(null != input){
				bitmap = BitmapFactory.decodeStream(input);
				imageCache.add(new LoadImage(imageUrl, new SoftReference<Bitmap>(bitmap)));
			}
		}
		
		return bitmap;
	}

	protected void onPostExecute(Bitmap bitmap) {
		if (null != bitmap) {
			int width = gView.getWidth();
			float scale = (float)width/bitmap.getWidth();
			bitmap = BitmapUtils.getRoundedCornerBitmap(bitmap, scale, 7, Config.ARGB_8888);
			gView.setImageBitmap(bitmap);
		} else {
			gView.setImageResource(R.drawable.cart_default);
		}
	}

	public boolean checkCacheImage() {
		if (imageCache.size() >= 5) {
			imageCache.remove(0);
		}
		return false;
	}

	public static HttpClient getHttpClient() 
	{
		HttpParams httpParams = new BasicHttpParams();
		
		//判断手机客户端连接的cmwap网络，设置代理
		if(AndroidUtils.isWap()){
			HttpHost proxy = new HttpHost("10.0.0.172", 80);
			httpParams.setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
		}
		
        HttpConnectionParams.setConnectionTimeout(httpParams, 60 * 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 60 * 1000);
        HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
       
        HttpClientParams.setRedirecting(httpParams, true);

        String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
        HttpProtocolParams.setUserAgent(httpParams, userAgent);

        return new DefaultHttpClient(httpParams);

    }
	
	/**
	 * 数据流连接
	 * 
	 * @param url
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @return InputStream
	 * @throws
	 */
	private InputStream doGet4stream(String url) {

		try {
			HttpClient mHttpClient = getHttpClient();

			HttpGet httpRequest = new HttpGet(url);
			HttpResponse httpResponse = mHttpClient.execute(httpRequest);

			mHttpClient = null;

			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				return httpResponse.getEntity().getContent();
			} else {
				Log.e("debug", "图片下载异常: " + httpResponse.getStatusLine().getStatusCode());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}
	
	class LoadImage {
		private String url;
		private SoftReference<Bitmap> reference;

		public LoadImage(String url, SoftReference<Bitmap> reference) {
			super();
			this.url = url;
			this.reference = reference;
		}

		public String getUrl() {
			return url;
		}

		public void setUrl(String url) {
			this.url = url;
		}

		public SoftReference<Bitmap> getReference() {
			return reference;
		}

		public void setReference(SoftReference<Bitmap> reference) {
			this.reference = reference;
		}
	}
}
